from channels.exceptions import StopConsumer
from channels.generic.websocket import WebsocketConsumer
from channels.generic.websocket import AsyncWebsocketConsumer
import json


class ChatConsumer(WebsocketConsumer):

    def websocket_connect(self, message):
        '''
        当有客户端向后端发送websocket连接请求时，自动触发该函数
        :param message:
        :return:
        '''
        # 服务器允许客户端创建连接
        self.accept()

    def websocket_receive(self, message):
        '''
        浏览器基于websocket向后端发送数据，自动触发接受消息，并且处理信息
        :param message:
        :return:
        '''
        # 输出消息
        print(message)
        # 服务端向前端回消息
        self.send('服务器收到了你的消息：%s' % (message['text']))

    def websocket_disconnect(self, message):
        '''
        客户端与服务端断开连接时，自动触发该函数
        :param message:
        :return:
        '''
        print('断开连接')
        raise StopConsumer()


class MyConsumer(AsyncWebsocketConsumer):
    room_id = None

    async def connect(self):
        print(self.scope)
        self.room_id = 'room_{}'.format(self.scope['url_route']['kwargs']['room_id'])
        self.from_client = str(self.scope["client"])

        print("room_id: ", self.room_id)
        print("self.channel_name: ", self.channel_name)

        # # Join room group
        print(f"将{self.channel_name}客户端对象添加到组group{self.room_id}中")
        await self.channel_layer.group_add(self.room_id, self.channel_name)
        await self.accept()

    async def disconnect(self, close_code):
        # # Leave room group
        await self.channel_layer.group_discard(self.room_id, self.channel_name)

    async def receive(self, text_data=None, bytes_data=None):
        print(text_data)

        text_data_json = json.loads(text_data)
        content = text_data_json['message']

        message = {
            'type': 'chat_message',
            'text': content,
            "from_client": self.from_client
        }

        print(message)
        await self.channel_layer.group_send(self.room_id, message)

    async def chat_message(self, event):
        # 处理消息的逻辑
        message = event['text']
        # print("self.scope", self.scope)
        # Send message to WebSocket
        print(":::", event["from_client"] + ":" + message)
        await self.send_json(event["from_client"] + ">>>" + message)

    async def send_json(self, message):
        await self.send(text_data=json.dumps({
            'message': message
        }))


class RoomConsumer(AsyncWebsocketConsumer):
    room_id = None

    async def connect(self):
        print(self.scope)
        self.room_id = 'room_{}'.format(self.scope['url_route']['kwargs']['room_id'])
        self.from_client = str(self.scope["client"])

        print("room_id: ", self.room_id)
        print("self.channel_name: ", self.channel_name)
        print("self.chennel_layer.group: ", self.channel_layer)

        # # Join room group
        print(f"将{self.channel_name}客户端对象添加到组group{self.room_id}中")
        await self.channel_layer.group_add(self.room_id, self.channel_name)
        await self.accept()

    async def disconnect(self, close_code):
        # # Leave room group
        await self.channel_layer.group_discard(self.room_id, self.channel_name)

    async def receive(self, text_data=None, bytes_data=None):
        message = {
            'type': 'chat_message',
            'text': text_data,
            "from_client": self.from_client,
            "channel_name": self.channel_name,
        }

        print(message)
        print(self.channel_layer.__dict__)
        print(self.channel_name)
        print(self.channel_layer.receive_buffer)
        print(type(self.channel_layer.receive_buffer))
        for key,value in self.channel_layer.receive_buffer.items():
            print(key, " ", value)

        await self.channel_layer.group_send(self.room_id, message)

    async def chat_message(self, event):
        # 处理消息的逻辑
        message = event['text']
        # print("self.scope", self.scope)
        # Send message to WebSocket
        print(":::", event["from_client"] + ":" + message)
        await self.send_json(event["from_client"] + ">>>" + message)

    async def send_json(self, message):
        await self.send(text_data=json.dumps({
            'message': message
        }))


class TestConsumer(AsyncWebsocketConsumer):

    async def connect(self):
        print(self.scope)
        param1 = self.scope['url_route']['kwargs']['param1']  # 获取路径参数
        param2 = self.scope['url_route']['kwargs']['param2']  # 获取路径参数
        param3 = self.scope['query_string'].decode()  # 获取查询参数

        print("param3: ", param3)


        # 处理传递的参数
        # ...

        await self.accept()

    async def receive(self, text_data):
        # 处理接收到的消息
        # ...
        pass

    async def disconnect(self, close_code):
        # 处理断开连接
        # ...
        pass